#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ==================================================
# @File    : operationFileControl
# @IDE     : PyCharm
# @Author  : liuxiangui
# @Date    : 2023/10/28 22:50
# @Describe: 
# ==================================================
import os
import yaml
from typing import Union
from configparser import ConfigParser
import pandas as pd
from openpyxl.worksheet.worksheet import Worksheet
from openpyxl.styles import PatternFill, Color, Border, Side, colors
from library.tools.file_tool.setting import root_path
from library.tools.file_tool.autoExcelWidthControl import autoExcelWidth


def read_yaml_to_dict(path: str) -> dict:
    """
    读取yaml文件为dict数据类型
    :param path: yaml文件路径
    :return: dict
    """
    with open(path, 'r') as f:

        data = yaml.load(f, yaml.FullLoader)
    return data


def save_dict_to_yaml(dict_value: dict, save_path: str) -> None:
    """
    保存dict为yaml文件
    :param dict_value: 存储dict字典
    :param save_path: 存储的yaml路径
    :return:
    """
    with open(save_path, 'w') as file:
        file.write(yaml.dump(dict_value, allow_unicode=True))


def read_ini_to_configparser(path: str) -> ConfigParser:
    """
    读取ini配置文件
    :param path: 路径
    :return: ConfigParser
    """
    config = ConfigParser()
    config.read(path)
    return config


def read_excel_to_dataframe(path: str, sheet=None, groupname=None) -> Union[pd.DataFrame, dict]:
    """
    读取excel文件转换为dataframe数据结构
    :param path: excel文件路径
    :param sheet: 读取的sheet页签，默认None读取第一个页签
    :param groupname: 分组的字段
    :return: 如果分组，返回分组key:dataframe键值对；如果不分组，返回整个页签的dataframe
    """
    df = pd.read_excel(path, sheet_name=sheet)
    if groupname:
        group = df.groupby(groupname)
        # groupkeys = [key for key in group.groups.keys()]
        return {key: value for key, value in group}
    else:
        return df


def save_dataframe_to_excel(excelpath: str, sheet_name: str, data: pd.DataFrame,
                            header_fill=True, is_border=True, is_auto_with=False) -> None:
    """
    保存dataframe数据结构到excel文件
    :param excelpath: excel文件路径
    :param data: dataframe数据
    :param sheet_name: sheet页签名字
    :param header_fill: 表头是否填充颜色，默认填充
    :param is_border: 单元格是否边框，默认黑色边框
    :param is_auto_with: 是否是自适应宽度，默认不
    :return:
    """
    writer = pd.ExcelWriter(excelpath, engine='openpyxl', mode='w')
    data.to_excel(writer, sheet_name, index=False)
    # df.to_excel(writer,"page01",index=False,startrow=tm.shape[0]+1)
    sheet = writer.sheets[sheet_name]  # type: Worksheet
    # 边框判断
    if is_border:
        border_set = Border(left=Side(style='thin', color=colors.BLACK),  # 左边框
                            right=Side(style='thin', color=colors.BLACK),  # 右边框
                            top=Side(style='thin', color=colors.BLACK),  # 上边框
                            bottom=Side(style='thin', color=colors.BLACK))  # 下边框
        for col in range(1, sheet.max_column + 1):
            for row in range(1, sheet.max_row + 1):
                sheet.cell(row, col).border = border_set
    # 表头颜色填充判断
    if header_fill:
        for col in range(1, sheet.max_column + 1):
            sheet.cell(1, col).fill = PatternFill(start_color=Color(rgb='fef1c1'), fill_type='solid')
    writer.close()
    # 自适应宽度判断
    if is_auto_with:
        autoExcelWidth(excelpath, sheet_name)

def read_csv_to_dataframe(path: str, groupname=None) -> pd.DataFrame:
    """
    读取csv文件转换为dataframe数据结构
    :param path: csv文件路径
    :param groupname: 分组的字段
    :return: 如果分组，返回分组key:dataframe键值对；如果不分组，返回整个页签的dataframe
    """
    df = pd.read_csv(path)
    if groupname is not None:
        group = df.groupby(groupname)
        return {key: value for key, value in group}
    else:
        return df


if __name__ == '__main__':
    data = read_excel_to_dataframe(os.path.join(root_path(), "testcase/feauture/casefile.xlsx"))
    print(data)
